/*
 * usart.c
 *
 *  Created on: 2025年9月1日
 *      Author: qazwe
 */
#include "fsl_device_registers.h"
#include "fsl_debug_console.h"
#include "usart.h"
#include "iap.h"
#include "fsl_lpuart.h"
#include "fsl_lpuart_edma.h"
#include "board.h"
#include <stdio.h>

uint8_t iap_flash_buf[FLASH_SECTOR_SIZE];
uint8_t iap_flash_buf_temp[FLASH_SECTOR_SIZE];
uint16_t iap_flash_buf_index = 0;
uint8_t Receive_Finish_Flag = 0;
uint8_t Receive_AllDone_Flag = 0;

void LPUART_IRQHandler(void)
{
    uint8_t data;
    if ((kLPUART_RxDataRegFullFlag)&LPUART_GetStatusFlags(LPUART_Receive))
    {
    	LPUART_ClearStatusFlags(LPUART_Receive,kLPUART_RxDataRegFullFlag);

    	data = LPUART_ReadByte(LPUART_Receive);
    	iap_flash_buf_temp[iap_flash_buf_index] = data;
    	iap_flash_buf_index++;
    	if(iap_flash_buf_index > (FLASH_SECTOR_SIZE-1))
    	{
    		iap_flash_buf_index = 0;
    	}
    }

    if ((kLPUART_IdleLineFlag)&LPUART_GetStatusFlags(LPUART_Receive))
    {
    	LPUART_ClearStatusFlags(LPUART_Receive,kLPUART_IdleLineFlag);
    	memcpy(iap_flash_buf, iap_flash_buf_temp, FLASH_SECTOR_SIZE);
    	Receive_Finish_Flag = 1;
    	//临时采用此方法判断是不是最后一包
    	if(iap_flash_buf_temp[FLASH_SECTOR_SIZE-1] == 0 && iap_flash_buf_temp[FLASH_SECTOR_SIZE-2] == 0 &&
    		iap_flash_buf_temp[FLASH_SECTOR_SIZE-3] == 0 && iap_flash_buf_temp[FLASH_SECTOR_SIZE-4] == 0)
    	{
    		Receive_AllDone_Flag = 1;
    	}
    	memset(iap_flash_buf_temp,0,FLASH_SECTOR_SIZE);
    }

    SDK_ISR_EXIT_BARRIER;
}

void UQ_UART_Init(void)
{

//    lpuart_config_t config;
//
//    LPUART_GetDefaultConfig(&config);
//    config.baudRate_Bps = BOARD_DEBUG_UART_BAUDRATE;
//    config.enableTx     = true;
//    config.enableRx     = true;
//
    memset(iap_flash_buf,0,FLASH_SECTOR_SIZE);
    memset(iap_flash_buf_temp,0,FLASH_SECTOR_SIZE);
//
//    LPUART_Init(LPUART_Receive, &config, DEMO_LPUART_CLK_FREQ);

    /* Enable RX interrupt. */
    LPUART_EnableInterrupts(LPUART_Receive, kLPUART_RxDataRegFullInterruptEnable | kLPUART_IdleLineInterruptEnable);
    EnableIRQ(BOARD_LPUART_IRQn);
}
int k = 0;
extern uint8_t NowFlash_Index;
//#define BUFFER_LEN 0x100
void iap_Handle(void)
{
	//循环写入扇区
	if(Receive_Finish_Flag)
	{
		Receive_Finish_Flag = 0;
		Flash_App(iap_flash_buf);
		if(Receive_AllDone_Flag)
		{
			Receive_AllDone_Flag = 0;
			NowFlash_Index = 0;
			Flash_UpdateFlag();

//			for(int i = 0;i<BUFFER_LEN*2;i++)
//			{
//				PRINTF(" %08X",*(volatile uint32_t *)(0x00030000 + i * 4));
//				if((i+1)%4 == 0)
//				{
//					PRINTF("\r\n");
//				}
//			}
			NVIC_SystemReset();
		}
	}
}
